<?php

namespace App\Http\Controllers\Api\Admin;

use App\ActivityBargain;
use App\ActivityGroup;
use App\ActivityGroupPrice;
use App\Classify;
use App\Goods;
use App\GoodSpu;
use App\GoodsSpu;
use App\Http\Services\FileManager;
use Illuminate\Http\Request;
use Auth;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ActivityController extends Controller
{
    /**
     * 拼团列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGroupList(Request $request){
        $classifyId = !is_null($request->get('classify_id')) ? $request->get('classify_id') : 0;
        $page       = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $keyword    = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $status     = !is_null($request->get('status')) ? $request->get('status') : '';

        $pageInfo=[
            'page'        => $page,
            'limit'       => $limit,
            'classify_id' => $classifyId,
            'keyword'     => $keyword,
            'status'      => $status
        ];

        /** @var ActivityGroup $activityGroup */
        $activityGroups = ActivityGroup::whereNull('deleted_at');

        $goodsArr = [];
        if($keyword != ''){
            /** @var Goods $goods */
            $goodsList = Goods::where('name','like','%'.trim($keyword).'%')->get();
            if(count($goodsList) > 0){
                foreach($goodsList as $goods){
                    array_push($goodsArr,$goods->id);
                }
            }
        }

        if($classifyId != 0){
            $goodsClassifyList = Goods::whereClassifyId($classifyId)->get();
            if(count($goodsClassifyList) > 0){
                foreach($goodsClassifyList as $goodsClassify){
                    array_push($goodsArr,$goodsClassify->id);
                }
            }
        }

        if(count($goodsArr) > 0){
            $activityGroups->whereIn('goods_id',$goodsArr);
        }

        //当前时间
        $time = date('Y-m-d H:i:s',time());

        //报名中
        if($status == 1){
            $activityGroups = $activityGroups->where('start_time','>',$time);
        }

        //进行中
        if($status == 2){
            $activityGroups = $activityGroups->where('end_time','>',$time)->where('start_time','<=',$time);
        }

        //已结束
        if($status == 3){
            $activityGroups = $activityGroups->where('end_time','<',$time);
        }

        $pageInfo['total'] = $activityGroups->count();

        $activityGroups = $activityGroups->orderBy('created_at','desc')->get();
        if(count($activityGroups) > 0){
            foreach($activityGroups as $activityGroup){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($activityGroup->goods_id)->first();
                if($thisGoods){
                    $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                    $thisGoods->classify_name = '';

                    $classify = Classify::whereId($thisGoods->classify_id)->first();
                    if($classify){
                        $thisGoods->classify_name = $classify->name;
                    }
                    $activityGroup->goods_info = $thisGoods;
                }else{
                    $activityGroup->goods_info = null;
                }

                if($time < $activityGroup->start_time){
                    $conduct = '报名中';
                    $activityStatus = 1;
                }elseif($time > $activityGroup->end_time){
                    $conduct = '已结束';
                    $activityStatus = 3;
                }else{
                    $conduct = '进行中';
                    $activityStatus = 2;
                }
                $activityGroup->activity_status      = $activityStatus;
                $activityGroup->activity_status_name = $conduct;
            }
        }

        return response()->json(['level' => 'success', 'message' => '获取成功', 'data' => $activityGroups,'page_info' => $pageInfo]);
    }

    /**
     * 拼团详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGroupDetail(Request $request)
    {
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var ActivityGroup $thisActivityGroup */
        $thisActivityGroup = ActivityGroup::whereId($id)->first();
        if ($thisActivityGroup) {
            /** @var Goods $thisGoods */
            $thisGoods = Goods::whereId($thisActivityGroup->goods_id)->first();
            if($thisGoods){
                $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                $thisGoods->classify_name = '';

                $classify = Classify::whereId($thisGoods->classify_id)->first();
                if($classify){
                    $thisGoods->classify_name = $classify->name;
                }
                $thisActivityGroup->goods_info = $thisGoods;
            }else{
                $thisActivityGroup->goods_info = null;
            }

            //当前时间
            $time = date('Y-m-d H:i:s',time());

            if($time < $thisActivityGroup->start_time){
                $conduct = '报名中';
                $activityStatus = 1;
            }elseif($time > $thisActivityGroup->end_time){
                $conduct = '已结束';
                $activityStatus = 3;
            }else{
                $conduct = '进行中';
                $activityStatus = 2;
            }
            $thisActivityGroup->activity_status      = $activityStatus;
            $thisActivityGroup->activity_status_name = $conduct;
        }

        return response()->json(['level' => 'success', 'message' => '获取成功', 'data' => $thisActivityGroup]);
    }

    /**
     * 设置拼团活动
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setActivityGroup(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);

        $ssn                       = $request->get('ssn');
        $name                      = $request->get('name');
        $mPrice                    = $request->get('m_price');
        $sPrice                    = $request->get('s_price');
        $imgId                     = $request->get('thumb_id');
        $info                      = $request->get('info');
        $integral                  = $request->get('integral');
        $id                        = !is_null($request->get('id')) ? $request->get('id') : 0;
        $isFreeShipping            = $request->get('isFreeShipping');
        $type                      = $request->get('type');
        $startTime                 = $request->get('start_time');
        $endTime                   = $request->get('end_time');
        $maxGroupNum               = $request->get('max_group_num');
        $groupEffectiveTime        = $request->get('group_effective_time');
        $status                    = $request->get('status');
        $takeGoodsTime             = $request->get('take_goods_time');
        $detail                    = $request->get('detail');

        if(is_null($groupEffectiveTime) || $groupEffectiveTime == '')
            return response()->json(['level' => 'error','message' => '请填写拼团有效时间']);

        if($groupEffectiveTime <= 0)
            return response()->json(['level' => 'error','message' => '拼团有效时间必须大于0的数字']);

        if(is_null($maxGroupNum) || $maxGroupNum == '')
            return response()->json(['level' => 'error','message' => '请填写最大拼团人数']);

        if($maxGroupNum <= 0)
            return response()->json(['level' => 'error','message' => '最大拼团时间必须大于0的数字']);

        if(is_null($startTime) || $startTime == '')
            return response()->json(['level' => 'error','message' => '请填写拼团开始时间']);

        if(is_null($endTime) || $endTime == '')
            return response()->json(['level' => 'error','message' => '请填写拼团结束时间']);

        /** @var ActivityGroup $newActivityGroup */
        $newActivityGroup = ActivityGroup::whereId($id)->first();
        if(!$newActivityGroup){
            $newActivityGroup = new ActivityGroup();

            $newGoods = new Goods();
        }else{
            /** @var Goods $newGoods */
            $newGoods = Goods::whereId($newActivityGroup->goods_id)->first();
        }

        if(!is_null($ssn))$newGoods->ssn                             = $ssn;
        if(!is_null($name))$newGoods->name                           = $name;
        if(!is_null($mPrice))$newGoods->m_price                      = $mPrice;
        if(!is_null($sPrice))$newGoods->s_price                      = $sPrice;
        if(!is_null($imgId))$newGoods->thumb_id                      = $imgId;
        if(!is_null($info))$newGoods->info                           = $info;
        if(!is_null($integral))$newGoods->integral                   = $integral;
        if(!is_null($isFreeShipping))$newGoods->is_free_shipping     = $isFreeShipping;
        if(!is_null($type))$newGoods->type                           = $type;
        if(!is_null($takeGoodsTime))$newGoods->take_goods_time       = $takeGoodsTime;
        if(!is_null($detail))$newGoods->detail                       = $detail;
        $newGoods->is_shop                                           = 1;
        $newGoods->save();

        $newActivityGroup->goods_id                                               = $newGoods->id;
        if(!is_null($maxGroupNum))$newActivityGroup->max_group_num                = $maxGroupNum;
        if(!is_null($groupEffectiveTime))$newActivityGroup->group_effective_time  = $groupEffectiveTime;
        if(!is_null($startTime))$newActivityGroup->start_time                     = $startTime;
        if(!is_null($endTime))$newActivityGroup->end_time                         = $endTime;
        if(!is_null($status))$newActivityGroup->status                            = $status;
        $newActivityGroup->save();


        $newGoodsSpu=GoodsSpu::whereGoodsId($newGoods->id)->get();

        if(count($newGoodsSpu)<1){
            $newGoodsSpu = new GoodsSpu();
            $newGoodsSpu->goods_id      = $newGoods->id;
            $newGoodsSpu->spu_name      = '标准';
            $newGoodsSpu->price         = $newGoods->s_price;
            $newGoodsSpu->status        = 1;
            $newGoodsSpu->save();
        }

        return response()->json(['level' => 'success','message' => '添加或修改成功',"data"=>$newGoods]);
    }

    /**
     * 删除拼团活动
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delActivityGroup(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var ActivityGroup $thatActivityGroup */
        $thatActivityGroup =ActivityGroup::whereId($id)->first();
        if(!$thatActivityGroup)
            return response()->json(["level"=>"error","message"=>"该活动不存在！"]);

        $thatGoods = Goods::whereId($thatActivityGroup->goods_id)->first();
        if(!$thatGoods)
            return response()->json(['level' => 'error','message' => '该砍价商品不存在']);

        $thatGoods->delete();

        $thatActivityGroup->delete();

        return response()->json(["level" => "success","message" => "删除成功","data" => $thatActivityGroup]);
    }
}
